package com.gzyj.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzyj.data.common.PageData;
import com.gzyj.data.web.cljk.CarTree;
import com.gzyj.data.web.cljk.CljkCarSearchParam;
import com.gzyj.data.web.cljk.OrgCarTreeDTO;
import com.gzyj.pojo.web.dept.BladeDept;
import com.gzyj.pojo.web.tpvdata.Tpvehdata;
import com.gzyj.web.config.SysConfig;
import com.gzyj.web.mapper.dept.BladeDeptMapper;
import com.gzyj.web.mapper.tpvdata.TpvehdataMapper;
import com.gzyj.web.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class CljkService {

    @Autowired
    private BladeDeptMapper bladeDeptMapper;


    private void setTreeData(BladeDept dep,
                             Map<String, OrgCarTreeDTO> treeNodeMap) {
        try {
            String depNodeId = "" + dep.getId();
            long parentId = (dep != null && dep.getParentId() != null) ? dep.getParentId() : 0;
            String strParentNodeId = "" + parentId;
            if (parentId == 0L) {
                strParentNodeId = "0";
            }

            OrgCarTreeDTO depNode = null;
            if ("777".equals(dep.getTreeCode())) {
                depNode = new OrgCarTreeDTO(depNodeId,
                        dep.getDeptName(), strParentNodeId, "");
            } else {
                depNode = new OrgCarTreeDTO(depNodeId,
                        dep.getDeptName(), strParentNodeId);
            }
            treeNodeMap.put(depNode.getId(), depNode);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private List<BladeDept> getAuthorizedDepList(int searchType, String searchKey, long userDeptId, long userId, Map<String, OrgCarTreeDTO> treeNodeMap) {

        BladeDept sparams = new BladeDept();
        sparams.setParentId(userDeptId);
        sparams.setSearchType(searchType);
        sparams.setDeptName(searchKey);
        //找出企业
        List<BladeDept> qyList = bladeDeptMapper.selectJianKongBladeDeptListByParams(sparams);
        Set<Long> orgIds = new LinkedHashSet<>();


        for (BladeDept dd : qyList) {
            try {
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(dd.getCityId())){
                    orgIds.add(Long.valueOf(dd.getCityId()));
                }
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(dd.getCountryId())){
                    orgIds.add(Long.valueOf(dd.getCountryId()));
                }

                if(org.apache.commons.lang3.StringUtils.isNotEmpty(dd.getProvinceId())){
                    orgIds.add(Long.valueOf(dd.getProvinceId()));
                }

                if(!orgIds.contains(dd.getParentId())){
                    // parentId 与省市县id 不相等

                    if(org.apache.commons.lang3.StringUtils.isNotEmpty(dd.getCountryId())){
                        dd.setParentId(Long.valueOf(dd.getCountryId()));
                    }else if(org.apache.commons.lang3.StringUtils.isNotEmpty(dd.getCityId())){
                        dd.setParentId(Long.valueOf(dd.getCityId()));
                    }else if(org.apache.commons.lang3.StringUtils.isNotEmpty(dd.getProvinceId())){
                        dd.setParentId(Long.valueOf(dd.getProvinceId()));
                    }


                }

            } catch (Exception error) {
                error.printStackTrace();
                continue;
            }
        }

        List<BladeDept> depList=new ArrayList<>();
        depList.addAll(qyList);

        if(orgIds.size()>0){
            QueryWrapper<BladeDept> w= new QueryWrapper<BladeDept>();
            w.in("id",new ArrayList<>(orgIds)).orderByAsc("parent_id","sort");
            List<BladeDept> orgList = bladeDeptMapper.selectList(w);
            depList.addAll(orgList);
        }







        Map<Integer, Integer> depIdMap = new HashMap<>();
        for (BladeDept dep : depList) {
            if (dep == null || depIdMap.containsKey(dep.getId())) {
                continue;
            }
            if (depIdMap.containsKey(dep.getId()) == false) {
                setTreeData(dep, treeNodeMap);
                depIdMap.put(dep.getId(), dep.getId());
            }

        }

        Collections.sort(depList, new Comparator<BladeDept>() {
            @Override
            public int compare(BladeDept o1, BladeDept o2) {
                if (o1.getId() == null) {
                    return -1;
                }

                return o1.getId().compareTo(o2.getId());
            }

        });


        return depList;
    }


    public CarTree buildDeptCarTree(CljkCarSearchParam param){
        CarTree carTree=new CarTree();
        if (param.getUserId()==null) {
            return new CarTree(0,0,0,new ArrayList<>());
        }

        long a = System.currentTimeMillis();
        ArrayList<OrgCarTreeDTO> treeData = new ArrayList<>();
        long userDeptId = SysConfig.ADMINDEPTID;
        Map<String, OrgCarTreeDTO> treeNodeMap = new HashMap<String, OrgCarTreeDTO>();

        // 用户分配的企业
        List<BladeDept> depList = this.getAuthorizedDepList(param.getSearchType(), param.getSearchKey(), userDeptId, param.getUserId(), treeNodeMap);


        // 创建车辆树节点
        Map<String,Integer> total=this.createVehicleTreeNode(userDeptId, param.getSearchType(), param.getOnlineType(), param.getVideoType(), param.getConnectType(), param.getRunType(), param.getSearchKey(), treeNodeMap,param.getSyxz());


        for (BladeDept dep : depList) {
            String childNodeId = "" + dep.getId();
            OrgCarTreeDTO node = treeNodeMap.get(childNodeId);
            if (node == null || node.getTotleNum() == 0) {
                continue;
            }
            String parentNodeId = "" + dep.getParentId();
            OrgCarTreeDTO parentNode = treeNodeMap.get(parentNodeId);
            if (parentNode != null) {
                parentNode.getChildren().add(node);
            } else {
                treeData.add(node);
            }

            String nodeText =
                    dep.getDeptName() + "(" + node.getOnlineNum()
                            + "/" + node.getTotleNum() + ")";
            node.setLabel(nodeText);

        }

        return new CarTree(total.get("total"),total.get("total")-total.get("offline"),total.get("offline"),treeData);

    }

    @Autowired
    private TpvehdataMapper tpvehdataMapper;

    private Map<String,Integer> createVehicleTreeNode(long userDeptId, int searchType, int onlineType, int videoType, int connectType, int runType, String searchKey, Map<String, OrgCarTreeDTO> treeNodeMap,String syxz) {
        Tpvehdata sparams = new Tpvehdata();
        sparams.setUserDeptId(userDeptId);
        sparams.setSearchKey(StringUtils.isNotEmpty(searchKey) ? searchKey.trim() : null);
        sparams.setSearchType(searchType);
        sparams.setOnlineType(onlineType);
        sparams.setVideoType(videoType);
        sparams.setOnlineTime(SysConfig.onlineTime * SysConfig.minuteSec);
        sparams.getParams().put("connectType", connectType);
        sparams.getParams().put("runType", runType);
        sparams.getParams().put("syxz", syxz);

        List<HashMap<String, String>> dataList = tpvehdataMapper.selectTpvehdataListByParams(sparams);
        AtomicInteger offline=new AtomicInteger();

        Map<String, String> nodeMap = new HashMap<String, String>();
        for (HashMap<String,String> rowData : dataList) {
            OrgCarTreeDTO treeSelectVn = new OrgCarTreeDTO();
            String parentNodeId = String.valueOf(rowData.get("depId"));
            String vehicleId = String.valueOf(rowData.get("vehicleId"));

            String gpsTime = "" + rowData.get("uploadTime");
            int secs = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, gpsTime));
            String stopTimes = secs > SysConfig.day7Sec ? ">7天" : secs > SysConfig.daySec ? ">1天" : DateUtils.secToTime(secs);
            boolean online = (0 < secs && secs < SysConfig.onlineTime * SysConfig.minuteSec) ? true : false;
            long velocity = Long.valueOf(String.valueOf(rowData.get("velocity")));
            String nodeDescr = String.valueOf(rowData.get("plateNo")) + "_" + String.valueOf(rowData.get("plateColor"));
            int alarm = Integer.valueOf(String.valueOf(rowData.get("alarm")));
            int acc = Integer.valueOf(String.valueOf(rowData.get("acc")));
            int zhongduanleixing = Integer.valueOf(String.valueOf(rowData.get("zhongduanleixing")));
            int platformconnectiontype = Integer.valueOf(String.valueOf(rowData.get("platformconnectiontype")));
            String yunyingshang = "" + rowData.get("yunyingshang");
            int flameout = Integer.valueOf(String.valueOf(rowData.get("flameout")));
            String stopStrTime = "" + rowData.get("stopTime");
            int stopTime = DateUtils.secStrToNowTime(stopStrTime);
            flameout = stopTime <= 0 ? secs : stopTime + secs;
            String flameoutTimes = flameout > SysConfig.day7Sec ? ">7天" : flameout > SysConfig.daySec ? ">1天" : DateUtils.secToTime(flameout);

            if (online) {
                String sendTime = "" + rowData.get("sendTime");
                if (velocity > 1) {

                    int secsGps = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, sendTime));
                    boolean isRun = (0 < secsGps && secsGps < SysConfig.onlineTime * SysConfig.minuteSec) ? true : false;
                    if (isRun) {
                        // gps时间在半小时内
                        nodeDescr += "_行驶[" + (int) velocity + "km/h]";
                        treeSelectVn.setStatus(SysConfig.iruncar);
                    } else {
                        // gps时间在半小时以前
                        int iflameout = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, sendTime));
                        flameoutTimes = iflameout > SysConfig.day7Sec ? ">7天" : iflameout > SysConfig.daySec ? ">1天" : DateUtils.secToTime(iflameout);
                        if (acc == 1) {
                            nodeDescr += "_停车[" + flameoutTimes + "]";
                            treeSelectVn.setStatus(SysConfig.istopcar);
                        } else {
                            nodeDescr += "_熄火[" + flameoutTimes + "]";
                            treeSelectVn.setStatus(SysConfig.iflameoutcar);
                        }
                    }
                } else {
                    int iflameout = 0;
                    if (DateUtils.secStrToNowTime(sendTime) > stopTime) {
                        // gps时间比停止时间还要远
                        iflameout = DateUtils.secToNowTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, sendTime));
                        flameoutTimes = iflameout > SysConfig.day7Sec ? ">7天" : iflameout > SysConfig.daySec ? ">1天" : DateUtils.secToTime(iflameout);
                    }

                    if (acc == 1) {
                        nodeDescr += "_停车[" + flameoutTimes + "]";
                        treeSelectVn.setStatus(SysConfig.istopcar);
                    } else {
                        nodeDescr += "_熄火[" + flameoutTimes + "]";
                        treeSelectVn.setStatus(SysConfig.iflameoutcar);
                    }
                }
            } else {
                if ("".equals(gpsTime) || SysConfig.neverOnlineTime.equals(gpsTime)) {
                    nodeDescr += "_从未上线";
                    treeSelectVn.setStatus(1);
                    treeSelectVn.setStatus(SysConfig.ineverOn);
                } else {
                    nodeDescr += "_离线[" + stopTimes + "]";
                    treeSelectVn.setStatus(SysConfig.iofflinecar);
                }
                offline.incrementAndGet();
            }
            treeSelectVn.setVideo(zhongduanleixing == 0 ? 1 : 2);
            treeSelectVn.setConnectType(platformconnectiontype);
            treeSelectVn.setVideoUrl(yunyingshang);
            treeSelectVn.setAlarm(alarm);
            treeSelectVn.setType(SysConfig.nodeTypeCar);
            treeSelectVn.setId(vehicleId);
            treeSelectVn.setPid(parentNodeId);
            treeSelectVn.setLabel(nodeDescr);
            treeSelectVn.setSimNo(rowData.get("zongduanid"));
            treeSelectVn.setVideoChannelNum(StringUtils.isNotEmpty(rowData.get("videoChannelNum"))?Integer.valueOf(String.valueOf(rowData.get("videoChannelNum"))):0);
            treeSelectVn.setAcc(Integer.valueOf(String.valueOf(rowData.get("acc"))));
            treeSelectVn.setVehNo(String.valueOf(rowData.get("plateNo")));
            treeSelectVn.setVehColor(String.valueOf(rowData.get("plateColor")));
            treeSelectVn.setPlatformConnectType(rowData.get("platformconnectiontype") != null && String.valueOf(rowData.get("platformconnectiontype")).length() > 0 ? Integer.parseInt(String.valueOf(rowData.get("platformconnectiontype"))) : 2);
            treeSelectVn.setAlarmNote(rowData.get("alarmNote") != null ? String.valueOf(rowData.get("alarmNote")) : null);
            if (nodeMap.containsKey(vehicleId) == false) {
                nodeMap.put(vehicleId, vehicleId);
                OrgCarTreeDTO parentNode = treeNodeMap.get(parentNodeId);
                if (parentNode != null) {
                    parentNode.getChildren().add(treeSelectVn);
                }
            }

            //计算总数
            OrgCarTreeDTO depNode = treeNodeMap.get(parentNodeId);
            while (depNode != null) {
                if (depNode.getId().equals(depNode.getPid())) {
                    depNode = null;
                } else {
                    depNode.setTotleNum(depNode.getTotleNum() + 1);
                    if (online) {
                        depNode.setOnlineNum(depNode.getOnlineNum() + 1);
                    }
                    parentNodeId = depNode.getPid();
                    depNode = treeNodeMap.get(parentNodeId);
                }
            }

        }

        Map<String,Integer> rs=new HashMap<>();
        rs.put("total",dataList.size());
        rs.put("offline",offline.intValue());

        return rs;
    }

}
